package cn.da.shuai.cool.system.api.controller;

import cn.da.shuai.cool.common.entity.R;
import cn.da.shuai.cool.system.model.entity.gen.CoolGenTable;
import cn.da.shuai.cool.system.model.entity.gen.CoolGenTableColumn;
import cn.da.shuai.cool.system.service.service.ICoolGenTableColumnService;
import cn.da.shuai.cool.system.service.service.ICoolGenTableService;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 */
@RestController
@RequestMapping("/tool/gen")
@Tag(name = "代码生成控制器")
public class CoolGenController {

    @Autowired
    private ICoolGenTableService genTableService;

    @Autowired
    private ICoolGenTableColumnService genTableColumnService;

    @GetMapping("/list")
    @Operation(summary = "获取代码生成列表")
    public R<List<CoolGenTable>> list(CoolGenTable genTable) {
        List<CoolGenTable> list = genTableService.selectGenTableList(genTable);
        return R.ok(list);
    }

    @GetMapping("/page")
    @Operation(summary = "获取代码生成分页列表")
    public R<Page<CoolGenTable>> page(CoolGenTable genTable, Page<CoolGenTable> page) {
        Page<CoolGenTable> list = genTableService.selectGenTablePage(genTable, page);
        return R.ok(list);
    }

    @GetMapping(value = "/db/list")
    @Operation(summary = "查询数据库列表")
    public R<List<CoolGenTable>> dataList(CoolGenTable genTable) {
        List<CoolGenTable> list = genTableService.selectDbTableList(genTable);
        return R.ok(list);
    }

    @GetMapping(value = "/db/page")
    @Operation(summary = "查询数据库分页列表")
    public R<Page<CoolGenTable>> dataPage(CoolGenTable genTable, Page<CoolGenTable> page) {
        Page<CoolGenTable> list = genTableService.selectDbTablePage(genTable, page);
        return R.ok(list);
    }

    @GetMapping(value = "/column/{tableId}")
    @Operation(summary = "查询业务表字段")
    public R<List<CoolGenTableColumn>> columnList(@PathVariable("tableId") Long tableId) {
        List<CoolGenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        return R.ok(list);
    }

    @GetMapping(value = "/preview/{tableId}")
    @Operation(summary = "预览代码")
    public R<Map<String, String>> preview(@PathVariable("tableId") Long tableId) {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return R.ok(dataMap);
    }

    @PostMapping("/importTable")
    @Operation(summary = "导入表结构")
    public R<Void> importTableSave(String tables) {
        String[] tableNames = tables.split(",");
        // 查询表信息
        List<CoolGenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return R.ok();
    }

    @GetMapping("/download/{tableName}")
    @Operation(summary = "下载代码")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    @GetMapping("/batchGenCode")
    @Operation(summary = "批量生成代码")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = tables.split(",");
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    @GetMapping("/{tableId}")
    @Operation(summary = "获取代码生成业务信息")
    public R<CoolGenTable> getInfo(@PathVariable Long tableId) {
        CoolGenTable table = genTableService.selectGenTableById(tableId);
        return R.ok(table);
    }

    @PutMapping
    @Operation(summary = "修改代码生成业务")
    public R<Void> editSave(@RequestBody CoolGenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return R.ok();
    }

    @DeleteMapping("/{tableIds}")
    @Operation(summary = "删除代码生成")
    public R<Void> remove(@PathVariable Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return R.ok();
    }

    @GetMapping("/synchDb/{tableName}")
    @Operation(summary = "同步数据库")
    public R<Void> synchDb(@PathVariable("tableName") String tableName) {
        genTableService.synchDb(tableName);
        return R.ok();
    }

    @PostMapping("/genCode/{tableName}")
    @Operation(summary = "生成代码（自定义路径）")
    public R<Void> genCode(@PathVariable("tableName") String tableName) {
        genTableService.generatorCode(tableName);
        return R.ok();
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"cool.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.writeObj(response.getOutputStream(), true, data);
    }
}